package com.example.demo.websocket;

import org.eclipse.jetty.websocket.api.Session;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketClose;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketConnect;
import org.eclipse.jetty.websocket.api.annotations.OnWebSocketMessage;
import org.eclipse.jetty.websocket.api.annotations.WebSocket;

import com.example.demo.entity.Message;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;

@WebSocket
public class ChatWebSocketHandler {
    private static Set<Session> sessions = Collections.synchronizedSet(new HashSet<>());
    private static ObjectMapper objectMapper = new ObjectMapper();

    @OnWebSocketConnect
    public void onConnect(Session session) {
        sessions.add(session);
        Message message = new Message();
        message.setMessage("用户加入群聊");
        message.setType("system");
        broadcastMessage(message);
    }

    @OnWebSocketMessage
    public void onMessage(Session session, String message) {
        Message msg = new Message();
        msg.setMessage(message);
        broadcastMessage(msg);
    }

    @OnWebSocketClose
    public void onClose(Session session, int statusCode, String reason) {
        sessions.remove(session);
        Message message = new Message();
        message.setMessage("用户已下线");
        message.setType("system");
        broadcastMessage(message);
    }

    private void broadcastMessage(Message message) {
        synchronized (sessions) {
            for (Session session : sessions) {
                try {
                    String jsonMessage = objectMapper.writeValueAsString(message);
                    session.getRemote().sendString(jsonMessage);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}